#include "HexagonParser.h"

#include "LineDescGroupParser.h"
#include "FillDescGroupParser.h"
#include "XformParser.h"
#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

HexagonParser::HexagonParser(
    DoubleParser *&_lengthParser
    , XformParser *&_xformParser
    , LineDescGroupParser *&_lineDescGroupParser
    , FillDescGroupParser *&_fillDescGroupParser
):    m_lengthParser(_lengthParser)
    , m_xformParser(_xformParser)
    , m_lineDescGroupParser(_lineDescGroupParser)
    , m_fillDescGroupParser(_fillDescGroupParser)
{

}

bool HexagonParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Hexagon());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("length")))
    {
        data = reader->attributes().value(QStringLiteral("length"));
        if (!m_lengthParser->parse(reader, data))
            return false;
        m_result->length = m_lengthParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("length: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Xform"))
        {
            if (!m_xformParser->parse(reader))
                return false;
            auto result = m_xformParser->result();
            m_result->xformOptional = Optional<Xform*>(result);
        }
        else if (m_lineDescGroupParser->isSubstitution(name))
        {
            if (!m_lineDescGroupParser->parse(reader))
                return false;
            auto result = m_lineDescGroupParser->result();
            m_result->lineDescGroupOptional = Optional<LineDescGroup*>(result);
        }
        else if (m_fillDescGroupParser->isSubstitution(name))
        {
            if (!m_fillDescGroupParser->parse(reader))
                return false;
            auto result = m_fillDescGroupParser->result();
            m_result->fillDescGroupOptional = Optional<FillDescGroup*>(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Hexagon *HexagonParser::result()
{
    return m_result.take();
}

}